import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:jyofservice/init/LoginPage.dart';
import 'package:jyofservice/util/webconfig.dart';
import 'package:mobpush_plugin/mobpush_plugin.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'AesUtil.dart';

class AppUpgrade {
  int _serviceVersionCode = 0;
  String? downloadUrl;
  //从后台获取版本信息
  Future getNewVersionApp(BuildContext context) async {
    bool isneedUpgrade = false;

    if (Platform.isIOS) {
      Response response =
          await Dio().get('https://itunes.apple.com/cn/lookup?id=1577145095');
      var dic = json.decode(response.toString());
      var result = dic["results"];
      if (result.length > 0) {
        var version = result[0]["version"];
        version = version.toString().replaceAll('.', '');
        print("packageInfo:$dic");
        print("$version");
        _serviceVersionCode = int.parse(version);
      }
    } else {
      SharedPreferences sharedPreferences =
          await SharedPreferences.getInstance();
      String? key = sharedPreferences.getString("key");
      String aesData = await (AesUtil.encodeBase64());
      var data = {"key": key, "ClientType": "phone", "ClientKey": aesData};
      Response response =
          await Dio().post(WebConfig().baseUrl + "DB/GetErWeiMa", data: data);
      if (response != null) {
        print(response.data.toString());

        _serviceVersionCode = int.parse(response.data["Data"][0]["banbenhao"]);
        downloadUrl =
            WebConfig().webapiurl + response.data["Data"][0]["fileurl"];
      }
    }

    await _checkVersionCode(context).then((value) {
      isneedUpgrade = value;
    });
    return {"upgrade": isneedUpgrade, "url": downloadUrl};
  }

  Future<bool> _checkVersionCode(BuildContext context) async {
    //获取当前版本信息
    bool needUpgrade = false;

    await PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
      var currentVersionCode;
      if (Platform.isIOS) {
        currentVersionCode = packageInfo.version;
        currentVersionCode = currentVersionCode.toString().replaceAll('.', '');
      } else {
        currentVersionCode = packageInfo.buildNumber;
      }

      print("哈哈哈：" + _serviceVersionCode.toString() + "," + currentVersionCode);

      needUpgrade = (_serviceVersionCode > int.parse(currentVersionCode));
    });

    print("hheheeh:" + needUpgrade.toString());
    return needUpgrade;
  }

  Future logout(BuildContext context) async {
    final option = await showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return new AlertDialog(
            title: Text('退出提醒'),
            content: Text('你确定要退出登录吗？'),
            actions: <Widget>[
              TextButton(
                child: Text('确定'),
                onPressed: () {
                  exit(context);
                },
              ),
              TextButton(
                child: Text('取消'),
                onPressed: () {
                  Navigator.pop(context);
                },
              )
            ],
          );
        });
  }

  exit(BuildContext context) async {
    MobpushPlugin.stopPush();
    SharedPreferences share = await SharedPreferences.getInstance();
    share.clear();
    if (Platform.isAndroid) {
//      SystemNavigator.pop();
      Navigator.pushAndRemoveUntil(context,
          MaterialPageRoute(builder: (context) {
        return LoginPage();
      }), (route) => route == null);
    } else {
      Navigator.pushAndRemoveUntil(context,
          MaterialPageRoute(builder: (context) {
        return LoginPage();
      }), (route) => route == null);
    }
  }
}
